package com.dmz.resold.apartment.csp;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author lee
 */
@Slf4j
public class SocketClientNew implements ISocketClient {

    public String send(String message, ConnectParam connectParam, ISocketLog iSocketLog) throws Exception {
        int port = connectParam.getPort(); // 访问端口
        String server_ip = connectParam.getIp(); // 访问IP
        log.info("ip:port{} {}",server_ip,port);
        int try_times = connectParam.getClientTryTimes(); // 重复访问次数
        Socket skt = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        boolean try_again = true;
        String resultMsg = "";

        while (try_times-- > 0 && try_again) {
            String msg = null;
            try {
                skt = new Socket(server_ip, port);
                log.info("客户端【Port=" + skt.getLocalPort() + "】成功连接到服务器端【IP=" + server_ip + ", Port=" + port + "】");
                os = skt.getOutputStream();
                is = skt.getInputStream();
                bos = new BufferedOutputStream(os);
                bos.write((message + "\r\n").getBytes("GBK"));
                bos.flush();


                br = new BufferedReader(new InputStreamReader(is, "GBK"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    resultMsg = line;
                }

                log.info("客机请求报文：{}", message);
                log.info("主机返回报文：{}", resultMsg);
                skt.close();
                try_again = false;
                log.info("与主机联机通信测试成功，线程退出");
            } catch (UnknownHostException e) {
                msg = e.getMessage();
                log.info("未知主机地址异常" + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                msg = e.getMessage();
                log.info("连接socket服务器时发生IO异常" + e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                msg = e.getMessage();
                log.info("连接socket服务器时发生异常" + e.getMessage());
                e.printStackTrace();
            } finally {
                if (null != skt && !skt.isClosed()) {
                    try {
                        skt.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return resultMsg;
    }

    private String readByLength(int size, BufferedInputStream in) throws IOException {
        StringBuffer rstr = new StringBuffer();

        byte[] data = null;
        int rSize = size;

        while (rSize > 0) {

            int tmp = 0;
            if (rSize < 2024) {
                tmp = rSize;
            } else {
                tmp = 1024;

            }

            data = new byte[tmp];
            int readsize = in.read(data, 0, tmp);
            if (readsize == -1)
                break;
            if (readsize > 0) {

                rSize = rSize - readsize;
                rstr.append(new String(data));
            }

        }


        return rstr.toString();
    }

}
